﻿using System;
using System.Collections.Generic;
using System.Linq;
using SqlSugar;
using DormMS.Common;
using DormMS.Model;
using System.Web;
using NLog;

namespace Infrastructure.Dao
{
    
    public class DbConfig
    {

        public static string ConnectionString = WsdConfig.GetConfigString("DefaultConnection");
        //过滤
        public static Dictionary<string, Func<KeyValueObj>> DefaultFilter = new Dictionary<string, Func<KeyValueObj>>() {
            //单表查询
            { "FalseDelte",()=>{return new KeyValueObj(){ Key=" (IsDeleted=0 )"};} },
            //多表查询
            { "FalseDelteJoin",()=>{return new KeyValueObj(){ Key=" (m.IsDeleted=0 )"};} },
        };

        private static Logger NLog = LogManager.GetLogger("Request");

        /// <summary>
        /// 全局配置类
        /// </summary>
        public class SugarConfigs
        {
            //流水号
            public static List<PubModel.SerialNumber> NumList = new List<PubModel.SerialNumber>(){
                //  new PubModel.SerialNumber(){TableName="Order", FieldName="OrderNo", GetNumFuncWithDb=db=>{ //事务中请使用GetNumFuncWithDb保证同一个DB对象,不然会出现死锁
                //      db.IsNoLock=false;
                //      var os = db.Queryable<OrderSerial>().FirstOrDefault(t=>t.Type=="W");
                //      if(os.Time.Date==DateTime.Today)
                //      {
                //          os.Number=os.Number+1;
                //      }
                //      else
                //      {
                //          os.Number=1;
                //          os.Time = DateTime.Today;
                //      }
                //      db.Update<OrderSerial>(os);
                //      db.IsNoLock=true;
                //      string dateNumber = DateTime.Today.ToString("yyMMdd");
                //      return "W"+dateNumber + os.Number.ToString("00000");
                //}},
                new PubModel.SerialNumber(){TableName="MemberRecharge", FieldName="PayNo",GetNumFuncWithDb=db=> {
                      db.CurrentFilterKey = "";
                      db.IsNoLock=false;
                      var os = db.Queryable<OrderSerial>().FirstOrDefault(t=>t.Type=="R");
                      if(os.Time.Date==DateTime.Today)
                      {
                          os.Number=os.Number+1;
                      }
                      else
                      {
                          os.Number=1;
                          os.Time = DateTime.Today;
                      }
                      db.Update<OrderSerial>(os);
                      db.IsNoLock=true;
                      string dateNumber = DateTime.Today.ToString("yyMMdd");
                      return "R"+dateNumber + os.Number.ToString("00000");
              }},
                new PubModel.SerialNumber(){TableName="Product", FieldName="Sku",GetNumFunc=()=> {
                  return "sku"+DateTimeHelper.DateTimeToTimestamp(true,DateTime.Now).ToString()+new Random().Next(1000).ToString("0000");
              }},
                new PubModel.SerialNumber(){TableName="ProductExchange", FieldName="BarCode",GetNumFunc=()=> {
                  return "p"+DateTimeHelper.DateTimeToTimestamp(true,DateTime.Now).ToString()+new Random().Next(1000).ToString("0000");
              }}
            };
        }
        //string dateNumber = DateTime.Today.ToString("yyMMdd");
        //                    return "W"+dateNumber + os.Number.ToString("00000");
        public static SqlSugarClient GetInstance()
        {
            try
            {
                var reval = new SqlSugarClient(ConnectionString);
                reval.SetFilterItems(DefaultFilter);//给查询添加默认过滤器 （所有查询加上 isdeleted=0）
                reval.AddDisableUpdateColumns("AddTime", "AddUserId");//添加禁止更新列
                reval.CurrentFilterKey = "FalseDelte";
                reval.SerializerDateFormat = "yyyy-MM-dd HH:mm";
                reval.SetSerialNumber(SugarConfigs.NumList);//设置流水号
                reval.IsEnableLogEvent = true;
                reval.LogEventStarting = (sql, pars) =>
                {//在这儿打段点可以查看生成的SQL语句
                    //System.Diagnostics.Debug.WriteLine(sql);
                    //System.Diagnostics.Debug.WriteLine(pars);
                    NLog.Info(sql);
                    NLog.Info(pars);
                };

                return reval;
            }
            catch (Exception ex)
            {
                throw new Exception("连接数据库出错，请检查您的连接字符串，和网络。 ex:" + ex.Message);
            }
        }

        public static SqlSugarClient GetInstance(string constr)
        {
            try
            {
                var reval = new SqlSugarClient(constr);
                reval.IsEnableLogEvent = true;
                reval.LogEventStarting = (sql, pars) =>
                {//在这儿打段点可以查看生成的SQL语句

                };
                return reval;
            }
            catch (Exception ex)
            {
                throw new Exception("连接数据库出错，请检查您的连接字符串，和网络。 ex:" + ex.Message);
            }
        }
    }
}
